package com.xiaofu.sort.merge;

import com.xiaofu.sort.Sort;

/**
 * @author: xiaofu
 * @DESCRIPTION: a technology seeker
 * @date: 2021-08-05 23:13
 */
public class MergeSort extends Sort {
    private Integer[] leftArray;

    @Override
    protected void sort() {
        leftArray = new Integer[array.length >> 1];
        sort(0, array.length);
    }

    /**
     * 对 【begin，end）范围的数据进行归并排序
     *
     * @param begin
     * @param end
     */
    private void sort(int begin, int end) {
        if (end - begin < 2)
            return;
        int mid = (begin + end) >> 1;
        sort(begin, mid);
        sort(mid, end);
        merge(begin, mid, end);
    }

    /**
     * 对 [begin, mid) 和 [mid,end) 范围的序列进行拼成一个有序序列
     *
     * @param begin
     * @param mid
     * @param end
     */
    private void merge(int begin, int mid, int end) {
        int li = 0, le = mid - begin;
        int ri = mid, re = end;
        int ai = begin;
        //备份左边数组
        for (int i = li; i < le; i++) {
            leftArray[i] = array[begin + i];
        }

        //如果左边的数组还没有结束
        while (li < le) {
            if (ri < re && cmpElement(array[ri], leftArray[li]) < 0) {
                array[ai++] = array[ri++];
            } else {
                array[ai++] = leftArray[li++];
            }
        }
    }
}
